package com.kpn.aurora.controller;

import cn.hutool.core.util.IdUtil;
import com.kpn.aurora.cfg.FileStorageProperties;
import com.kpn.aurora.util.MultipartFileUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class UploadController {

    @Autowired
    private FileStorageProperties fileStorageProperties;

    @PostMapping("/upload/bio/test")
    public String upload(@RequestParam("file") MultipartFile aaa) throws IOException {
//获取文件原始名称
        String prefix = MultipartFileUtil.getMultipartFilePrefix(aaa);
        String suffix = MultipartFileUtil.getMultipartFileSuffix(aaa);

        System.err.println(prefix);
        System.err.println(suffix);

        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = fileStorageProperties.getUploadDir() + "/files/" + dateFormat;

        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + IdUtil.simpleUUID() + suffix;

        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) {
            dateDir.mkdirs();
        }

        //处理文件上传
        aaa.transferTo(new File(dateDir, newFileName));

        System.err.println(ResourceUtils.getURL("classpath:").getPath());
        return "ok";

    }

    @PostMapping("/upload/nio/test")
    public String uploadByNio(@RequestParam("file") MultipartFile aaa) throws IOException {
        String prefix = MultipartFileUtil.getMultipartFilePrefix(aaa);
        String suffix = MultipartFileUtil.getMultipartFileSuffix(aaa);

        System.err.println(prefix);
        System.err.println(suffix);

        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = fileStorageProperties.getUploadDir() + "/files/" + dateFormat;

        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + IdUtil.simpleUUID() + suffix;
        Path targetLocation = Paths.get(dateDirPath + "/" + newFileName);
        Files.copy(aaa.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return newFileName;

    }


    //20210613014857e4ff4bfdd9e641e2b79d197ce1eea525

    @GetMapping("download")
    public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
        //获取打开方式
        openStyle = openStyle == null ? "attachment" : openStyle;
        //获取文件信息
        String imgNamePrefix = id;
        //点击下载链接更新下载次数
        if ("attachment".equals(openStyle)) {
            System.err.println("下载模式");
        }
        if ("inline".equals(openStyle)) {
            System.err.println("预览模式");
        }

        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realpath = fileStorageProperties.getUploadDir() + "/files/2021-06-13/";
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath, imgNamePrefix + ".jpg"));
        //附件下载
        response.setHeader("content-disposition", openStyle + ";fileName="
                + URLEncoder.encode(imgNamePrefix + ".jpg", "UTF-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    @GetMapping("/preview/{fileFullName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileFullName,
                                                 HttpServletRequest request) throws MalformedURLException {
        String realpath = fileStorageProperties.getUploadDir() + "/files/2021-06-13/";
        Path targetLocation = Paths.get(realpath +  fileFullName);
        Resource resource = new UrlResource(targetLocation.toUri());
        if (resource.exists()){
            System.err.println("resource已存在");
        }

        String contentType = null;
        try{
            contentType = request.getServletContext()
                    .getMimeType(resource.getFile().getAbsolutePath());
        }catch (IOException ex){
            System.err.println("Could not determine file type");
        }

        if (contentType == null){
            contentType = "application/octet-stream";
        }

        System.err.println(contentType);
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "inline; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }



}
